<template>
  <div style="height: 50px;">
    <van-nav-bar ref="VanNavBarDmo" :title="title" left-text="返回" left-arrow @click-left="onClickLeft" fixed />
  </div>
  <van-form ref="from_arr" @submit="onSubmit">
    <FromList :FromArr="from.list" labelWidth="6.1rem" @blur="blur" />
    <van-field required v-model="value" name="uploader" label="附件">
      <template #input>
        <van-uploader v-model="fileList.list" :after-read="afterRead" :max-count="3"
          accept="image/png,image/jpeg,image/jpg" :max-size="20000 * 1024" @oversize="onOversize" @delete="fileDelete" />
      </template>
    </van-field>
    <div style="margin: 16px;margin-top: 50px;">
      <van-button round block type="primary" native-type="submit" :disabled="+CounterStore.isSubmit === 1">
        提交
      </van-button>
    </div>
    <div style="margin: 16px;margin-top: 20px;" v-if="!title?.indexOf('编辑')">
      <van-button round block type="warning" @click="onDelete" :disabled="+CounterStore.isSubmit === 1">
        删除
      </van-button>
    </div>
  </van-form>
</template>

<script setup>
import FromList from '../FillIn/FromList.vue'
import { education, theTitleTechnicalPost, skill } from './addressEdit'
import { Base64 } from 'js-base64'
import { insetEducationInfo, insertTitleInfo, insertSkillInfo, deleteEducation, deleteEmployeeTitle, deleteEmployeeSkill } from '@/api/addressEdit.js'
import { Toast } from 'vant';
import { useCounterStore } from '@/pinia/user.js'
import { upload, deleteUploadFile, getObjectInfo, getDeadStatusObject } from '@/api/uploader'


const CounterStore = useCounterStore()
// 路由节点
const Route = useRoute()
const Router = useRouter()

let query = {}
const a = JSON.parse(Base64.decode(Route.query.data))





// 表单
const from = reactive({ list: [] })
// 获取url中携带的参数
let title = ref('')

if (a.id) {
  getObjectInfo({ employeeId: CounterStore.employeeId, otherId: a.id, type: a.type }).then(res => {
    query = a
    query.item = { ...res.message };
    title.value = query.name;
    init()
  })
} else {
  query = a
  title.value = query.name;
  init()
}


const fileList = reactive({ list: [] })

const value = ref(0)

watch(() => fileList.list, (v) => { v.length === 0 ? value.value = '' : value.value = value.length })

async function init() {
  let res
  if (query.name.includes('添加')) {
    const name = query.name.includes('学历') ? 'educationId' : query.name.includes('职称') ? 'titleId' : query.name.includes('技能') ? 'skillId' : ''
    const type = query.name.includes('学历') ? '1' : query.name.includes('职称') ? '3' : query.name.includes('技能') ? '2' : ''
    const otherId = CounterStore.counter[name]
    if (otherId) {
      res = await getDeadStatusObject({ employeeId: CounterStore.employeeId, otherId, type })
      query.item = res.message
    }
  }
  // theTitleTechnicalPost
  if (query.key === 'education') from.list = await education(query.item)
  if (query.key === 'skill') from.list = await skill(query.item)
  if (query.key === 'theTitleTechnicalPost') from.list = await theTitleTechnicalPost(query.item)
  if (query?.item?.uploadFile?.length) setFileList()

}

function setFileList() {
  query.item.uploadFile.forEach(item => {
    fileList.list.push({
      content: `data:image/jpeg;base64,${item.fileCode}`,
      fileName: item.fileName
    })
  })
  value.value = fileList.list.length
}


const fileDelete = async (file) => {
  let type
  let otherId
  const item = query.item
  if (query.key === 'education') {
    otherId = item.educationId
    type = 4
  }
  // 职称
  if (query.key === 'theTitleTechnicalPost') {
    otherId = item.titleId
    type = 6
  }
  // 技能证书
  if (query.key === 'skill') {
    otherId = item.skillId
    type = 5
  }
  const res = await deleteUploadFile({ fileName: file.fileName, id: CounterStore.employeeId, type, otherId })
  Toast(res.message)
}

// // 提交按钮
// const disabledButton = ref(false)
// 返回上一层
function onClickLeft() { history.back() }
// 保存并提交
async function onSubmit(type) {
  // disabledButton.value = true
  let sava = 'null'
  if (type !== 1) {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    })
    sava = '1'
  }
  fromValue.employeeId = CounterStore.employeeId
  const item = query.item
  let res
  if (query.key === 'education') res = await insetEducationInfo({ ...fromValue, educationId: type === 1 ? '' : item.educationId }, sava)
  if (query.key === 'theTitleTechnicalPost') res = await insertTitleInfo({ ...fromValue, titleId: type === 1 ? '' : item.titleId }, sava)
  if (query.key === 'skill') res = await insertSkillInfo({ ...fromValue, skillId: type === 1 ? '' : item.skillId }, sava)
  if (res.success) {
    // Toast.clear()
    // Dialog.confirm({ message: `保存成功是否离开当前页面`, }).then(() => { Router.go(-1) }).catch(
    //   () => {
    //     from.list.forEach(item => {
    //       item.disabled = true
    //       item.type = 1
    //     })
    //   }
    // );
    if (type !== 1) {
      Toast.success({
        message: '保存成功',
        forbidClick: true,
        duration: 1000
      })
      // CounterStore.defaultCounter()
      if (query.item.default) {
        const a = {}
        a[query.item.default] = null
        CounterStore.setCounter(a)
      }
    }

  } else {
    // disabledButton.value = false
    Toast.fail({
      message: res.message,
      forbidClick: true,
      duration: 1000
    });

  }
  return res
}





const afterRead = async (file) => {
  const item = query.item
  if (!item.employeeId) item.employeeId = CounterStore.employeeId
  const id = item.educationId ? item.educationId : item.titleId ? item.titleId : item.skillId ? item.skillId : 0
  const type = item.educationId ? 4 : item.titleId ? 6 : item.skillId ? 5 : 0
  file.status = 'uploading';
  file.message = '上传中...';
  const formdata = new FormData()
  formdata.append('uploadFile', file.file);
  formdata.append('employeeId', item.employeeId);
  formdata.append('otherId', id);
  formdata.append('type', type);
  const res = await upload(formdata)
  if (res.success) {
    file.status = 'done'
    file.message = '上传成功'
    file.fileName = res.message
  } else {
    file.status = 'failed'
    file.message = res.message
  }
};

const onOversize = (file) => {
  Toast('文件大小不能超过 20MB');
}

// 返回的填写的内容
let fromValue
async function blur(value = {}) {
  fromValue = value
  if (!query.item) {
    const item = CounterStore.counter
    let text
    const data = {}
    if (query.key === 'education') text = 'educationId'
    if (query.key === 'skill') text = 'skillId'
    if (query.key === 'theTitleTechnicalPost') text = 'titleId'
    if (!item[text]) {
      const res = await onSubmit(1)
      if (res.success) {
        data[text] = res.message
        CounterStore.setCounter(data)
      }
    } else {
      data[text] = item[text]
    }
    query.item = data
    query.item.default = text
  }
}


// watch(value, (value) => {
//   console.log(value)
// })
// onMounted(() => {
//   init()
// })



// 删除
async function onDelete() {
  Toast.loading({
    message: '删除中...',
    forbidClick: true,
  })
  let res
  const item = query.item
  const data = { id: item.employeeId }
  if (query.key === 'education') {
    data.educationId = item.educationId
    res = await deleteEducation(data)
  }
  // 职称
  if (query.key === 'theTitleTechnicalPost') {
    data.titleId = item.titleId
    res = await deleteEmployeeTitle(data)
  }
  // 技能证书
  if (query.key === 'skill') {
    data.skillId = item.skillId
    res = await deleteEmployeeSkill(data)
  }


  if (res.success) {
    Toast.success(res.message)
    setTimeout(() => { Router.go(-1) }, 1000)
  } else {
    Toast.fail(res.message)
  }
}

</script>
